package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.dao.persist.repository.*;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.entity.SpuDetail;
import cn.tedu.csmall.product.pojo.param.SpuAddNewParam;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.ISpuService;
import cn.tedu.csmall.product.util.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 处理SPU的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class SpuServiceImpl implements ISpuService {

    @Value("${csmall.crud.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IdUtils idUtils;
    @Autowired
    private IBrandRepository brandRepository;
    @Autowired
    private ICategoryRepository categoryRepository;
    @Autowired
    private IAlbumRepository albumRepository;
    @Autowired
    private ISpuRepository spuRepository;
    @Autowired
    private ISpuDetailRepository spuDetailRepository;

    public SpuServiceImpl() {
        log.info("创建业务对象：SpuServiceImpl");
    }

    @Override
    public void addNew(SpuAddNewParam spuAddNewParam) {
        log.debug("开始处理【新增SPU】的业务，参数：{}", spuAddNewParam);
        // 检查品牌：是否存在，是否启用
        Long brandId = spuAddNewParam.getBrandId();
        BrandStandardVO brand = brandRepository.getStandardById(brandId);
        if (brand == null) {
            String message = "新增SPU失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        if (brand.getEnable() == 0) {
            String message = "新增SPU失败，品牌已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        // 检查类别：是否存在，是否启用，是否不包含子级
        Long categoryId = spuAddNewParam.getCategoryId();
        CategoryStandardVO category = categoryRepository.getStandardById(categoryId);
        if (category == null) {
            String message = "新增SPU失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        if (category.getEnable() == 0) {
            String message = "新增SPU失败，类别已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        if (category.getIsParent() == 1) {
            String message = "新增SPU失败，选择的类别不允许包含子级类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        // 检查相册：是否存在
        Long albumId = spuAddNewParam.getAlbumId();
        AlbumStandardVO album = albumRepository.getStandardById(albumId);
        if (album == null) {
            String message = "新增SPU失败，相册数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        // 获取SPU ID
        Long spuId = idUtils.generateSpuId();

        // 创建SPU对象
        Spu spu = new Spu();
        // 复制属性值
        BeanUtils.copyProperties(spuAddNewParam, spu);
        // 补全属性值：id >>> 暂时随便写
        spu.setId(spuId);
        // 补全属性值：brand_name, category_name >>> 此前检查时的查询结果
        spu.setBrandName(brand.getName());
        spu.setCategoryName(category.getName());
        // 补全属性值：sales, comment_count, positive_comment_count >>> 0
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);
        // 补全属性值：is_deleted, is_published, is_new_arrival, is_recommend >>> 0
        spu.setIsDeleted(0);
        spu.setIsPublished(0);
        spu.setIsNewArrival(0);
        spu.setIsRecommend(0);
        // 补全属性值：is_checked >>> 0, check_user >>> null, gmt_check >>> null
        spu.setIsChecked(0);
        // 插入SPU数据
        int rows = spuRepository.insert(spu);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        // 创建SpuDetail对象
        SpuDetail spuDetail = new SpuDetail();
        // 补全属性值：spu_id >>> 与以上Spu的ID相同
        spuDetail.setSpuId(spuId);
        // 补全属性值：detail >>> 来自参数
        spuDetail.setDetail(spuAddNewParam.getDetail());
        // 插入SpuDetail数据
        rows = spuDetailRepository.insert(spuDetail);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public SpuStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询SPU详情】的业务，参数：{}", id);
        SpuStandardVO queryResult = spuRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "根据ID查询SPU详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        log.debug("即将返回SPU详情：{}", queryResult);
        return queryResult;
    }

    @Override
    public SpuFullInfoVO getFullInfoById(Long id) {
        log.debug("开始处理【根据ID查询SPU完整信息】的业务，参数：{}", id);
        SpuFullInfoVO queryResult = spuRepository.getFullInfoById(id);
        if (queryResult == null) {
            String message = "根据ID查询SPU详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        log.debug("即将返回SPU详情：{}", queryResult);
        return queryResult;
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum) {
        log.debug("开始处理【查询SPU列表】的业务，页码：{}", pageNum);
        PageData<SpuListItemVO> pageData = spuRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询SPU列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<SpuListItemVO> pageData = spuRepository.list(pageNum, pageSize);
        return pageData;
    }
}
